const queryString = require('querystring');
const handleBlogRouter = require('./src/router/blog');
const handleUserRouter = require('./src/router/user');

// 处理post请求,data中的数据
const getPostData = req => {
  return new Promise((resolve, reject) => {
    if (req.method != 'POST') {
      resolve({});
      return;
    }
    if (req.headers['content-type'] !== 'application/json') {
      resolve({})
      return;
    }
    let postData = '';
    req.on('data', chunk => {
      postData += chunk.toString();
    })
    req.on('end', () => {
      if (!postData) {
        resolve({})
        return;
      }
      resolve(
        JSON.parse(postData)
      );
    })
  })
}

const serverHandle = (req, res) => {
  res.setHeader('Content-type', 'application/json');

  //解析path
  req.path = req.url.split('?')[0];
  //解析query
  req.query = queryString.parse(req.url.split('?')[1]);

  //解析cookie
  req.cookies = {};
  const cookieStr = req.headers.cookie || '';
  cookieStr.split(';').forEach(item => {
    if (!item) {
      return;
    }
    const arr = item.split('=');
    const key = arr[0].trim();
    const value = arr[1];
    req.cookies[key] = value;
  });

  // 处理post data
  getPostData(req).then(postData => {
    req.body = postData;

    //处理博客路由
    const blogData = handleBlogRouter(req, res);
    if (blogData) {
      blogData.then(data => {
        res.end(JSON.stringify(data))
      });
      return
    }

    //处理用户路由
    const userData = handleUserRouter(req, res);
    if (userData) {
      userData.then(data => {
        res.end(JSON.stringify(data))
      })
      return
    }
  })
}

module.exports = serverHandle
